import { defineStore } from 'pinia'
import { authConfig } from '@/config'

export const useUserStore = defineStore('user', {
  state: () => ({
    isAuthenticated: false,
    user: null,
    token: null
  }),
  
  getters: {
    isLoggedIn: (state) => state.isAuthenticated,
    userInfo: (state) => state.user,
    authToken: (state) => state.token
  },
  
  actions: {
    async login(username, password) {
      try {
        // 模拟登录验证
        if (username === 'admin' && password === 'admin123') {
          this.isAuthenticated = true
          this.user = { 
            id: 1,
            username: 'admin', 
            name: '管理员',
            avatar: '',
            role: 'admin'
          }
          this.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTY3MzM0NzIwMH0.mock_token_123456'
          
          // 存储到localStorage
          localStorage.setItem(authConfig.tokenKey, this.token)
          localStorage.setItem('user_info', JSON.stringify(this.user))
          
          return { success: true, message: '登录成功' }
        }
        
        return { success: false, message: '用户名或密码错误' }
      } catch (error) {
        return { success: false, message: '登录失败，请重试' }
      }
    },
    
    logout() {
      this.isAuthenticated = false
      this.user = null
      this.token = null
      
      // 清除localStorage
      localStorage.removeItem(authConfig.tokenKey)
      localStorage.removeItem('user_info')
    },
    
    checkAuth() {
      const token = localStorage.getItem(authConfig.tokenKey)
      const userInfo = localStorage.getItem('user_info')
      
      if (token && userInfo) {
        try {
          this.isAuthenticated = true
          this.token = token
          this.user = JSON.parse(userInfo)
          return true
        } catch (error) {
          this.logout()
          return false
        }
      }
      
      return false
    },
    
    updateUserInfo(userInfo) {
      this.user = { ...this.user, ...userInfo }
      localStorage.setItem('user_info', JSON.stringify(this.user))
    }
  }
})